﻿using System;
using System.Drawing;
using System.Windows.Forms;
using System.Xml;
using MG_POS_PC.Util;
using System.Data;
using System.IO;

namespace MG_POS_PC
{
    public partial class NetworkSetting : BaseForm
    {

        private string filename = System.Environment.CurrentDirectory + "\\" + FileName.xmlIps;
        private static Boolean isAdd = true;
        private DataTable dt = null;


        public NetworkSetting()
        {
            InitializeComponent();
            this.basePanel.Top = (this.ClientSize.Height - this.basePanel.Height) / 2;
        }

        private void NetworkSetting_Load(object sender, EventArgs e)
        {
            dt = FormatUtil.GenerateDataTable(filename);
            Display(dt);
            initFields();
        }
       

        private void Display(DataTable dt)
        {
            listIP.GridLines = true;
            listIP.FullRowSelect = true;

            listIP.Clear();
            listIP.Columns.Add("A", 20, HorizontalAlignment.Center);
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                listIP.Columns.Add(dt.Columns[i].ColumnName.ToString().Trim(), 100, HorizontalAlignment.Center);
            }

            for (int j = 0; j < dt.Rows.Count; j++)
            {
                ListViewItem lvi = listIP.Items.Add(dt.Rows[j][0].ToString());
                lvi.SubItems.Add(dt.Rows[j][0].ToString());
                lvi.SubItems.Add(dt.Rows[j][1].ToString());
                lvi.SubItems.Add(dt.Rows[j][2].ToString());
                lvi.SubItems.Add(dt.Rows[j][3].ToString());
            }

            for (int i = 0; i < listIP.Items.Count; i++)
            {
                if (i % 2 != 0)
                    listIP.Items[i].BackColor = Color.Wheat;
                else
                    listIP.Items[i].BackColor = Color.MintCream;
            }
        }

        private string getLocalIP()
        {
            return NetworkUtil.GetLocalIP();
        }

        private void initFields()
        {
            this.txtComputerIP.Text = getLocalIP();
            setTxt(txtStation, "", false);
            setTxt(txtName, "", false);
            setTxt(txtIP, "", false);

        }

        private void setTxt(TextBox txt, string str, bool enable)
        {
            txt.Text = str;
            txt.Enabled = enable;
        }

        private string getTxt(TextBox txt)
        {
            return txt.Text.ToString().Trim();
        }

        private void setBtn(Button btn, bool enable)
        {
            btn.Enabled = enable;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            isAdd = true;
            initFields();
            setTxt(txtStation, "", true);
            setTxt(txtName, "", true);
            setTxt(txtIP, "", true);
            txtStation.Focus();
            setBtn(btnAdd, false);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Delete?", "Confirm Message", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                if (this.listIP.SelectedItems.Count > 0)
                {
                    string station = listIP.SelectedItems[0].SubItems[1].Text.Trim();
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.Load(filename);
                    XmlNodeList nodeList = xmlDoc.SelectSingleNode("IPs").ChildNodes;
                    foreach (XmlNode xn in nodeList)
                    {
                        XmlElement xe1 = (XmlElement)xn;
                        if ((xe1.Attributes.Count > 0 && xe1.GetAttribute("Station") == station))
                        {
                            xe1.RemoveAll();
                        }
                    }
                    xmlDoc.Save(filename);
                    Display(FormatUtil.GenerateDataTable(filename));
                    initFields();
                }
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!validateFields())
            {
                return;
            }
            else
            {
                if (MessageBox.Show("Save?", "Confirm Message", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    string station = getTxt(txtStation);
                    string name = getTxt(txtName);
                    string ip = getTxt(txtIP);

                    if (isAdd)
                    {
                        setBtn(btnAdd, true);

                        XmlDocument xmlDoc = new XmlDocument();
                        xmlDoc.Load(filename);
                        XmlNodeList nodeList = xmlDoc.SelectSingleNode("IPs").ChildNodes;
                        foreach (XmlNode xn in nodeList)
                        {
                            XmlElement xe1 = (XmlElement)xn;
                            if (xe1.Attributes.Count > 0 && xe1.GetAttribute("IP") == ip)
                            {
                                MessageBox.Show("IP Address Exists!");
                                return;
                            }
                        }

                        XmlNode root = xmlDoc.SelectSingleNode("IPs");
                        XmlElement xe2 = xmlDoc.CreateElement("IP");
                        xe2.SetAttribute("IP", ip);
                        xe2.SetAttribute("Name", name);
                        xe2.SetAttribute("Station", station);
                        xe2.SetAttribute("Connection", "");
                        root.AppendChild(xe2);
                        xmlDoc.Save(filename);
                    }
                    else
                    {
                        XmlDocument xmlDoc1 = new XmlDocument();
                        xmlDoc1.Load(filename);
                        XmlNodeList nodeList = xmlDoc1.SelectSingleNode("IPs").ChildNodes;
                        foreach (XmlNode xn in nodeList)
                        {
                            XmlElement xe1 = (XmlElement)xn;
                            if (xe1.GetAttribute("Station") == station)
                            {
                                xe1.SetAttribute("IP", ip);
                                xe1.SetAttribute("Name", name);
                                break;
                            }
                        }
                        xmlDoc1.Save(filename);
                    }
                    initFields();
                    Display(FormatUtil.GenerateDataTable(filename));
                }
            }
        }


        private bool validateFields()
        {
            if (getTxt(txtStation) == "" || !Regexlib.isValidInt(getTxt(txtStation)))
            {
                txtStation.Focus();
                MessageBox.Show("Station is empty or Invalid Station number!");
                return false;
            }
            if (getTxt(txtName) == "")
            {
                txtName.Focus();
                MessageBox.Show("Name is empty!");
                return false;
            }
            if (getTxt(txtIP) == "" || !Regexlib.IsValidIp(getTxt(txtIP)))
            {
                txtIP.Focus();
                MessageBox.Show("IP is empty or Invalid IP!");
                return false;
            }
            return true;

        }

        private void btnTestConnection_Click(object sender, EventArgs e)
        {
            setBtn(btnTestConnection, false);

            dt = FormatUtil.GenerateDataTable(filename);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string ip = dt.Rows[i][2].ToString().Trim();
                dt.Rows[i][3] = NetworkUtil.cmdPing(ip);
            }
            Display(dt);
            setBtn(btnTestConnection, true);
        }

        private void writeLog(string mess)
        {
            FileStream fs = new FileStream(@"c:/mcWindowsService.txt", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter m_streamWriter = new StreamWriter(fs);
            m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
            m_streamWriter.WriteLine(" -->" + mess);
            m_streamWriter.Flush();
            m_streamWriter.Close();
            fs.Close();
        }

        private void listIP_SelectedIndexChanged(object sender, EventArgs e)
        {
            isAdd = false;
            dt = FormatUtil.GenerateDataTable(filename);
            if (this.listIP.SelectedItems.Count > 0)
            {
                string station = listIP.SelectedItems[0].SubItems[1].Text.Trim();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i][0].ToString() == station)
                    {
                        setTxt(txtStation, dt.Rows[i][0].ToString(), false);
                        setTxt(txtName, dt.Rows[i][1].ToString(), true);
                        setTxt(txtIP, dt.Rows[i][2].ToString(), true);
                    }
                }
            }
        }
        
    }
}
